from client_core import SsdevClient
import json
import logging

Default_bbp_url = 'http://127.0.0.1:8080/bbp-server/'
Default_bbp_system_tenant_id = 'bsoft'
Default_sale_package_code = 'sale-package-balance'
Default_tenant_id = 'dzgl'
Default_username = 'system'
Default_password = '123'

BALANCE_SOFT_NAME = "对账管理"
BALANCE_SOFT_CODE = 'bsoft-dzgl'
BBP_SOFT_CODE = 'bsoft-bbp'

Modules = [
    {"moduleId": "5b64049050ffad3e700bc44f", "parentId": "5b64049050ffad3e700bc44b", "na": "机构配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": True,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc450", "parentId": "5b64049050ffad3e700bc44b", "na": "部门配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc451", "parentId": "5b64049050ffad3e700bc44b", "na": "人员配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 2, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5f361ffe850a413eadcd5cf6", "parentId": "5b64049050ffad3e700bc44b", "na": "工作站配置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 3, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc452", "parentId": "5b64049050ffad3e700bc44c", "na": "角色配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": True,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc455", "parentId": "5b64049050ffad3e700bc44c", "na": "功能配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc453", "parentId": "5b64049050ffad3e700bc44d", "na": "字典配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": True,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc454", "parentId": "5b64049050ffad3e700bc44d", "na": "参数配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5be9261d4bacae34f4948e8e", "parentId": "5b64049050ffad3e700bc44d", "na": "字典回收站", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 2, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5be948c14bacae3e4419ab3e", "parentId": "5b64049050ffad3e700bc44d", "na": "参数限定配置", "leaf": True,
     "checked": True, "module": True, "children": [], "index": 3, "depth": 2, "expanded": False, "expandable": True,
     "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False, "isFirst": False,
     "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "", "hrefTarget": "", "qtip": "",
     "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "634f5fb88350ff55debffd7e", "parentId": "5b64049050ffad3e700bc44d", "na": "参数导出", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 4, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "634fc8a9df1b3f68383f40f5", "parentId": "5b64049050ffad3e700bc44d", "na": "字典导出", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 5, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc456", "parentId": "5b64049050ffad3e700bc44e", "na": "基础数据账户配置",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": True, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5b64049050ffad3e700bc458", "parentId": "5b64049050ffad3e700bc44e", "na": "租户及功能配置",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5c219c47f6387122885107d3", "parentId": "5c219c2df6387122885107c5", "na": "日历日期维护", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": True, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5c3da51081918a16ec7d20db", "parentId": "5c219c2df6387122885107c5", "na": "日历日期分组维护",
     "des": "", "leaf": True, "checked": True, "module": True, "children": [], "index": 1, "depth": 2,
     "expanded": False, "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False,
     "isLast": True, "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False,
     "href": "", "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d030e5f381ee25f4434eeed", "parentId": "5d030e47381ee25f4434eee7", "na": "消息定义", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": True, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d0c9a5c381ee204ec51b253", "parentId": "5d030e47381ee25f4434eee7", "na": "消息管理", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d19aa5a886b10431c21b7eb", "parentId": "5d030e47381ee25f4434eee7", "na": "消息订阅", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 2, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d41596bcdd2d41d68a3c074", "parentId": "5d030e47381ee25f4434eee7", "na": "发送公告", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 3, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d3ab38dd00161313b972055", "parentId": "5d316eab71265627bce7f9f9", "na": "用户设置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": True, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d3eadd0d0016157dc2b529c", "parentId": "5d316eab71265627bce7f9f9", "na": "系统设置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d3eae95d0016157dc2b52af", "parentId": "5d316eab71265627bce7f9f9", "na": "全局设置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 2, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d664ac48ae05c0b1bc45f62", "parentId": "5d316eab71265627bce7f9f9", "na": "单点登陆", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 3, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d5cccc801b27545c8ba864c", "parentId": "5d5cccc801b27545c8ba864a", "na": "属性类型配置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 0, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": True, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d5cccc801b27545c8ba8652", "parentId": "5d5cccc801b27545c8ba864a", "na": "实体配置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 1, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": False,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""},
    {"moduleId": "5d5cd3f701b27541e4a2362f", "parentId": "5d5cccc801b27545c8ba864a", "na": "应用配置", "des": "",
     "leaf": True, "checked": True, "module": True, "children": [], "index": 2, "depth": 2, "expanded": False,
     "expandable": True, "cls": "", "iconCls": "", "icon": "", "glyph": "", "root": False, "isLast": True,
     "isFirst": False, "allowDrop": True, "allowDrag": True, "loaded": False, "loading": False, "href": "",
     "hrefTarget": "", "qtip": "", "qtitle": "", "qshowDelay": 0, "visible": True, "text": ""}]


class SalePackageService(object):
    service_id = 'bbp.salePackage'

    def __init__(self, client: SsdevClient):
        self.client = client

    def save(self, tenant_id, tenant_name, method='create'):
        req_body = {"tenantId": "bsoft", "saleType": "1", "cd": tenant_id, "na": tenant_name, "des": "", "py": "",
                    "wb": "", "zj": ""}
        return self.client.invoke(SalePackageService.service_id, 'save', req_body, method)

    def locate(self, create_rsp: dict):
        req_body = {"id": create_rsp['id'], "saleType": "1",
                    "cd": create_rsp['cd'], "na": create_rsp['na'],
                    "des": "", "py": create_rsp['py'], "wb": create_rsp['wb'], "zj": "",
                    "instr": create_rsp['instr'], "active": True,
                    "saleTypeText": create_rsp['saleTypeText']}
        return self.client.invoke(SalePackageService.service_id, 'locate', [req_body], 10)

    def sales(self):
        url = self.client.bbp_base_url + '/sys.tet.sale.dic'
        str_rsp = self.client.http_request(url, 'GET', {}, None)
        return json.loads(str_rsp)['items']

    def find_all(self, sale_id, soft_id):
        req_body = {"softId": soft_id, "saleId": sale_id}
        return self.client.invoke(SalePackageService.service_id, 'findAll', req_body)

    def save_module(self, sale_id, soft_id, modules):
        return self.client.invoke(SalePackageService.service_id, 'saveModule', soft_id, sale_id, modules)


class TenantConfigService(object):
    service_id = 'bbp.tenantConfig'

    def __init__(self, client: SsdevClient):
        self.client = client

    def create_tenant(self, tenant_code, tenant_name, sale_id=None):
        req_body = {"cd": tenant_code, "na": tenant_name,
                    "saleId": sale_id,
                    "categoryId": None, "entryTime": "2023-01-01T00:00:00.000Z",
                    "quitTime": None, "des": "", "py": "", "wb": "", "zj": ""}

        print('create_tenant:' + json.dumps(req_body))
        return self.client.invoke(TenantConfigService.service_id, 'createTenant', req_body)

    def load_apps(self):
        return self.client.invoke(TenantConfigService.service_id, 'loadApps')

    def load_module_tree(self, tenant_id, app_id):
        return self.client.invoke(TenantConfigService.service_id, 'loadModuleTree', tenant_id, None, app_id)

    def save_tenant_module(self, tenant_id, app_id, modules):
        return self.client.invoke(TenantConfigService.service_id, 'saveTenantModule', tenant_id, app_id, modules)

    def update_tenant(self, tenant_id, tenant_name, sale_id):
        req_body = {"id": tenant_id, "cd": tenant_id, "na": tenant_name, "saleId": sale_id,
                    "categoryId": "", "entryTime": "2023-01-01T00:00:00.000Z", "quitTime": None, "des": "",
                    "mnemonicCode": "dzgl,cmtg,", "py": "", "wb": "", "zj": ""}

        return self.client.invoke(TenantConfigService.service_id, 'updateTenant', req_body)

    def load_diff_data(self, tenant_id):
        return self.client.invoke(TenantConfigService.service_id, 'loadDiffData', tenant_id)


class ModuleService(object):
    service_id = 'bbp.module'

    def __init__(self, client: SsdevClient):
        self.client = client

    def find_soft(self):
        return self.client.invoke(ModuleService.service_id, 'findSoft')

    def exist_soft(self, soft_code):
        soft_list = self.client.invoke(ModuleService.service_id, 'findSoft')['body']
        soft_id = None
        find_soft = list(filter(lambda s: s['cd'] == soft_code, soft_list))
        if len(find_soft) > 0:
            soft_id = find_soft[0]['id']
        return len(find_soft) > 0, soft_id

    def get_soft(self, soft_id):
        return self.client.invoke(ModuleService.service_id, 'getSoft', soft_id)

    def save_soft(self, soft_code, soft_name):
        req_obj = {"cd": soft_code, "na": soft_name, "softType": "1", "belongOrgId": "", "icon": "", "url": "",
                   "loader": None, "des": "", "py": "", "wb": "", "zj": ""}

        return self.client.invoke(ModuleService.service_id, 'saveSoft', req_obj, 'create')

    # saveModuleCategory
    def save_module_category(self, ca_code, ca_name, soft_id):
        req_obj = {"na": ca_name, "cd": ca_code, "parent": "", "icon": "", "des": "", "py": "", "wb": "", "zj": "",
                   "softId": soft_id}
        return self.client.invoke(ModuleService.service_id, 'saveModuleCategory', req_obj, 'create')

    def get_module_category(self, module_category_id):
        return self.client.invoke(ModuleService.service_id, 'getModuleCategory', module_category_id)

    def get_module_category_by_soft(self, soft_id):
        url = self.client.bbp_base_url + '/sys.auth.fu.dic?parentKey=' + soft_id
        rsp = self.client.http_request(url, 'GET', {}, None)
        return json.loads(rsp)

    def exist_module_category_with_soft(self, soft_id, module_category_code):
        items = self.get_module_category_by_soft(soft_id)['items']
        ca_id = None

        find_category = list(
            filter(lambda i: isinstance(i['mcode'], str) and i['mcode'].startswith(module_category_code), items))
        if len(find_category) > 0:
            ca_id = find_category[0]['key']
        return len(find_category) > 0, ca_id

    def get_modules_by_ca(self, ca_id):
            url = self.client.bbp_base_url + '/sys.auth.fu.dic?parentKey=' + ca_id
            rsp = self.client.http_request(url, 'GET', {}, None)
            return json.loads(rsp)

    def exist_module_with_ca_id(self, module_code, ca_id):
        items = self.get_modules_by_ca(ca_id)['items']
        module_id = None
        find_items = list(filter(lambda s: s['properties']['cd'] == module_code, items))
        if len(find_items) > 0:
            module_id = find_items[0]['key']
        return len(find_items) > 0, module_id

    def save_module(self, module_ca: dict, module_code, module_name):
        req_obj = {"cd": module_code, "na": module_name, "des": "", "isShow": "1",
                   "softId": module_ca['softId'], "moduleCategoryId": module_ca['id'], "moduleType": None,
                   "py": "", "wb": "", "zj": "", "ref": ""}
        return self.client.invoke(ModuleService.service_id, 'saveModule', req_obj, 'create')

    def get_module(self, module_id):
        return self.client.invoke(ModuleService.service_id, 'getModule', module_id)

    def save_module_prop(self, module_id, key, value, portal_type='WEB_DESKTOP_NATIVE', method='create'):
        req_obj = {"id": module_id, "moduleId": module_id, "portalType": portal_type, "key": key, "value": value}
        return self.client.invoke(ModuleService.service_id, 'saveModuleProp', req_obj, method)

    # findModuleProp
    def find_module_prop(self, module_id, portal_type='WEB_DESKTOP_NATIVE'):
        return self.client.invoke(ModuleService.service_id, 'findModuleProp', module_id, portal_type)

    def exist_module_prop(self, key, module_id):
        properties = self.find_module_prop(module_id)['body']
        found_item = [properties for p in properties if p['key'] == key]
        if len(found_item) > 0:
            return found_item[0]
        else:
            return None


class DictionaryService(object):
    def __init__(self, client: SsdevClient):
        self.client = client

    def find_all_dict_catalog(self, page_no=0, page_size=100):
        return self.client.invoke('bbp.dicConfig', 'findAllDicCa', page_no, page_size)

    def create_dict_catalog(self, code: str, title: str, parent=''):
        return self.client.invoke('bbp.dicConfig', 'createDicCa',
                                  {"id": "",
                                   "cd": code,
                                   "na": title,
                                   "mnemonicCode": "",
                                   "type": "",
                                   "softId": "",
                                   "des": "",
                                   "py": "",
                                   "wb": "", "zj": "", "parent": parent})

    def query_dict_catalog_by_id(self, ca_id: str):
        return self.client.invoke('bbp.dicConfig', 'queryDicCaById', ca_id)

    def query_dict_catalog_by_code(self, ca_code: str):
        content = self.find_all_dict_catalog()['body']
        for item in content:
            if item['cd'] == ca_code:
                return item
        return None

    def exist_dict_catalog_by_code(self, ca_code: str):
        content = self.find_all_dict_catalog()['body']
        for item in content:
            if item['cd'] == ca_code:
                return True
        return False

    def create_dict(self, code: str, title: str, catalog_id: str = '', dict_type: str = '1'):
        req = {"id": code,
               "cd": code,
               "na": title,
               "dicType": dict_type,
               "ver": None, "dicLevel": 0, "storageType": "1",
               "public": False, "usageType": None, "usageDes": None,
               "des": None, "modifyDate": None, "mnemonicCode": None,
               "py": None, "wb": None, "zj": None,
               "dicCategoryId": catalog_id}
        return self.client.invoke('bbp.dicConfig', 'createDic', req)

    def query_dict(self, code: str):
        return self.client.invoke('bbp.dicConfig', 'getDictionary', code)

    def exist_dict(self, code: str):
        exist_rsp = self.query_dict(code)
        return 200 == exist_rsp['code']

    def setup_dict(self, code, title, catalog):
        if not self.exist_dict(code):
            self.create_dict(code, title, catalog['id'])
        return self.query_dict(code)['body']

    def load_dict_all_items(self, code, page_no=0, page_size=25):
        return self.client.invoke('bbp.dicConfig', 'loadDicAllItems', code, '', True, page_no, page_size)

    def exist_dict_item(self, dict_code, item_code):
        if self.exist_dict(dict_code):
            exist_all = self.load_dict_all_items(dict_code)['body']['items']
            for item in exist_all:
                if item['id'] == item_code:
                    return True
            return True
        return False

    def create_dict_item(self, dict_code, item_code, item_name):
        return self.client.invoke('bbp.dicConfig', 'createDictionaryItem', dict_code, item_code, item_name, '')

    def setup_dict_item(self, dict_code, item_code, item_name):
        if not self.exist_dict_item(dict_code, item_code):
            self.create_dict_item(dict_code, item_code, item_name)


def main(main_client: SsdevClient):
    service = DictionaryService(main_client)
    catalog_code = 'catalog.dz'
    if not service.exist_dict(catalog_code):
        service.create_dict_catalog(catalog_code, '对账管理')

    catalog = service.query_dict_catalog_by_code(catalog_code)
    catalog_id = catalog['id']

    # dict_notice_name = service.setup_dict('noticename', '通知名称', catalog)
    # dict_date_result = service.setup_dict('dateResult', '日对账结果', catalog)
    # dict_settle_status = service.setup_dict('settleStatus', '结算状态', catalog)
    # dict_key_compare = service.setup_dict('keyCompare', '对比主键', catalog)
    #
    # service.setup_dict('modifyStatus', '差异处理状态', catalog)
    # service.setup_dict('chargeType', '收费类型', catalog)
    # service.setup_dict('fieldCompare', '对比键', catalog)
    # service.setup_dict('bankName', '银行', catalog)
    #
    # service.setup_dict('channelType', '数据渠道类型', catalog)
    # service.setup_dict('resultScripe', '对账结果说明', catalog)
    # service.setup_dict('trade.result', '对账结果', catalog)
    # service.setup_dict('balanceResult', '对账结果', catalog)
    #
    # service.setup_dict('balanceType', '对账类型', catalog)
    # service.setup_dict('compareType', '运算', catalog)
    # service.setup_dict('dateType', '数据获取类型', catalog)
    # service.setup_dict('tradeScene', '渠道场景', catalog)
    #
    # service.setup_dict('fileStatus', '文件获取状态', catalog)
    # service.setup_dict('tradeType', '交易类型', catalog)
    # service.setup_dict('channelCode', '渠道代码', catalog)
    # service.setup_dict('modifyType', '处理类型', catalog)
    #
    # service.setup_dict('tradeResult', '交易结果', catalog)
    # service.setup_dict('balanceStatus', '对账状态', catalog)
    # service.setup_dict('noticeType', '通知类型', catalog)
    # service.setup_dict('useStatus', '启用状态', catalog)
    #
    # service.setup_dict('isbalance', '是否参与对账', catalog)
    # service.setup_dict('selQuarter', '季度', catalog)
    # service.setup_dict('fileType', '对账文件类型', catalog)
    # service.setup_dict('selMonth', '月份', catalog)

    service.setup_dict_item('noticename', '1', '差异订单通知')
    service.setup_dict_item('noticename', '2', '待结算日账单通知')

    service.setup_dict_item('dateResult', '1', '正确')
    service.setup_dict_item('dateResult', '2', '差异')
    service.setup_dict_item('dateResult', '3', '未执行')
    service.setup_dict_item('dateResult', '4', '失败')

    service.setup_dict_item('settleStatus', '1', '已结算')
    service.setup_dict_item('settleStatus', '2', '待结算')

    service.setup_dict_item('keyCompare', '1', '应收订单号')
    service.setup_dict_item('keyCompare', '2', '渠道订单号')
    service.setup_dict_item('keyCompare', '3', '最终渠道订单号')

    # service.setup_dict('modifyStatus', '差异处理状态', catalog)
    service.setup_dict_item('modifyStatus', '1', '待处理')
    service.setup_dict_item('modifyStatus', '2', '已处理')
    # service.setup_dict('chargeType', '收费类型', catalog)
    service.setup_dict_item('chargeType', '1', '现金')
    service.setup_dict_item('chargeType', '2', 'POS机')
    service.setup_dict_item('chargeType', '3', '预充值')
    service.setup_dict_item('chargeType', '4', '未知渠道')
    # service.setup_dict('fieldCompare', '对比键', catalog)
    service.setup_dict_item('fieldCompare', '1', '订单号')
    service.setup_dict_item('fieldCompare', '2', '金额')
    service.setup_dict_item('fieldCompare', '3', '交易日期')
    service.setup_dict_item('fieldCompare', '4', '机构')
    service.setup_dict_item('fieldCompare', '5', '操作员')
    # service.setup_dict('bankName', '银行', catalog)
    service.setup_dict_item('bankName', '0102', '中国工商银行')

    # service.setup_dict('channelType', '数据渠道类型', catalog)
    service.setup_dict_item('channelType', '1', '应收渠道')
    service.setup_dict_item('channelType', '2', '实收渠道')
    service.setup_dict_item('channelType', '3', '最终实收渠道')
    # service.setup_dict('resultScripe', '对账结果说明', catalog)
    service.setup_dict_item('resultScripe', '1', '单边(实收有,应收无)')
    service.setup_dict_item('resultScripe', '2', '单边(实收无,应收有)')
    service.setup_dict_item('resultScripe', '3', '金额不一致')
    service.setup_dict_item('resultScripe', '4', '实收当日成对收退费记录，匹配单号:')
    # service.setup_dict('trade.result', '对账结果', catalog)
    service.setup_dict_item('trade.result', '1', '未对账')
    service.setup_dict_item('trade.result', '2', '已对账')
    service.setup_dict_item('trade.result', '3', '全部')
    # service.setup_dict('balanceResult', '对账结果', catalog)
    service.setup_dict_item('balanceResult', '1', '正确')
    service.setup_dict_item('balanceResult', '2', '差异待处理')
    service.setup_dict_item('balanceResult', '3', '差异已处理')
    #
    # service.setup_dict('balanceType', '对账类型', catalog)
    service.setup_dict_item('balanceType', '1', '次日对账')
    # service.setup_dict('compareType', '运算', catalog)
    service.setup_dict_item('compareType', '1', '完全一致')
    service.setup_dict_item('compareType', '2', '忽略大小写一致')
    # service.setup_dict('dateType', '数据获取类型', catalog)
    service.setup_dict_item('dateType', '1', '自动获取')
    service.setup_dict_item('dateType', '2', '手动获取')
    # service.setup_dict('tradeScene', '渠道场景', catalog)
    service.setup_dict_item('tradeScene', 'app', 'App应用支付')
    service.setup_dict_item('tradeScene', 'face', '人脸支付')
    service.setup_dict_item('tradeScene', 'h5', 'Html5支付')
    service.setup_dict_item('tradeScene', 'insurance', '线上医保支付')
    service.setup_dict_item('tradeScene', 'microPay', '二维码被扫')
    service.setup_dict_item('tradeScene', 'miniApp', '小程序支付')
    service.setup_dict_item('tradeScene', 'mp', '公众号支付')
    service.setup_dict_item('tradeScene', 'noPass', '免密支付')
    service.setup_dict_item('tradeScene', 'qrCode', '二维码主扫')
    service.setup_dict_item('tradeScene', 'unionCode', '聚合二维码支付')
    #
    # service.setup_dict('fileStatus', '文件获取状态', catalog)
    service.setup_dict_item('fileStatus', '-1', '失败')
    service.setup_dict_item('fileStatus', '0', '待获取')
    service.setup_dict_item('fileStatus', '1', '成功')
    # service.setup_dict('tradeType', '交易类型', catalog)
    service.setup_dict_item('tradeType', '-1', '错误')
    service.setup_dict_item('tradeType', '1', '收款')
    service.setup_dict_item('tradeType', '2', '退款')
    # service.setup_dict('channelCode', '渠道代码', catalog)
    service.setup_dict_item('channelCode', 'aliapy', '支付宝')
    service.setup_dict_item('channelCode', 'e-CNY', '数字人民币')
    service.setup_dict_item('channelCode', 'hihis', 'HiHIS')
    service.setup_dict_item('channelCode', 'payment', '聚合支付')
    service.setup_dict_item('channelCode', 'quickPay', '银联云闪付')
    service.setup_dict_item('channelCode', 'weChat', '微信')
    service.setup_dict_item('channelCode', 'whis', 'WHis')
    # service.setup_dict('modifyType', '处理类型', catalog)
    service.setup_dict_item('modifyType', '1', '退费')
    service.setup_dict_item('modifyType', '2', '应收记录不参与对账')
    service.setup_dict_item('modifyType', '3', '渠道记录不参与对账')
    #
    # service.setup_dict('tradeResult', '交易结果', catalog)
    service.setup_dict_item('tradeResult', '0', '失败')
    service.setup_dict_item('tradeResult', '1', '成功')
    # service.setup_dict('balanceStatus', '对账状态', catalog)
    service.setup_dict_item('balanceStatus', '1', '未对账')
    service.setup_dict_item('balanceStatus', '2', '已对账')
    # service.setup_dict('noticeType', '通知类型', catalog)
    service.setup_dict_item('noticeType', '1', '站内通知')
    # service.setup_dict('useStatus', '启用状态', catalog)
    service.setup_dict_item('useStatus', '1', '开启')
    service.setup_dict_item('useStatus', '2', '关闭')
    #
    # service.setup_dict('isbalance', '是否参与对账', catalog)
    service.setup_dict_item('isbalance', '1', '是')
    service.setup_dict_item('isbalance', '2', '否')
    # service.setup_dict('selQuarter', '季度', catalog)
    service.setup_dict_item('selQuarter', '1', 'Q1')
    service.setup_dict_item('selQuarter', '2', 'Q2')
    service.setup_dict_item('selQuarter', '3', 'Q3')
    service.setup_dict_item('selQuarter', '4', 'Q4')
    # service.setup_dict('fileType', '对账文件类型', catalog)
    service.setup_dict_item('fileType', 'csv', '逗号分隔文件(*.csv)')
    service.setup_dict_item('fileType', 'json', 'Json文件(*.json)')
    service.setup_dict_item('fileType', 'txt', '文本文件(*.txt)')
    service.setup_dict_item('fileType', 'xlsx', 'Excel文件(*.xlsx)')
    service.setup_dict_item('fileType', 'xml', 'Xml文件(*.xml)')
    # service.setup_dict('selMonth', '月份', catalog)
    service.setup_dict_item('selMonth', '1', '1月')
    service.setup_dict_item('selMonth', '2', '2月')
    service.setup_dict_item('selMonth', '3', '3月')
    service.setup_dict_item('selMonth', '4', '4月')
    service.setup_dict_item('selMonth', '5', '5月')
    service.setup_dict_item('selMonth', '6', '6月')
    service.setup_dict_item('selMonth', '7', '7月')
    service.setup_dict_item('selMonth', '8', '8月')
    service.setup_dict_item('selMonth', '9', '9月')
    service.setup_dict_item('selMonth', '10', '10月')
    service.setup_dict_item('selMonth', '11', '11月')
    service.setup_dict_item('selMonth', '12', '12月')

    print(service.exist_dict_item('noticename', '3'))


def system_client() -> SsdevClient:
    system_tenant = Default_bbp_system_tenant_id
    username = Default_username
    password = Default_password

    client = SsdevClient(Default_bbp_url, Default_bbp_url)
    rsp = client.my_roles(system_tenant, username, password)
    my_roles = rsp['body']
    token = client.fetch_token(system_tenant, username, my_roles[0])
    print(token)

    return client


def tenant_client() -> SsdevClient:
    tenant = Default_tenant_id
    username = Default_username
    password = Default_password

    client = SsdevClient(Default_bbp_url, Default_bbp_url)
    rsp = client.my_roles(tenant, username, password)
    my_roles = rsp['body']
    token = client.fetch_token(tenant, username, my_roles[0])
    print(token)

    return client


def create_tenant():
    sale_package_code = Default_sale_package_code
    tenant_code = Default_tenant_id

    client = system_client()
    service = SalePackageService(client)
    module_service = ModuleService(client)

    create_sale_rsp = service.save(sale_package_code, BALANCE_SOFT_NAME)

    print('create_sale_rsp', create_sale_rsp)

    create_sale_id = create_sale_rsp['body']['id']

    if create_sale_rsp['code'] == 200:
        locate_rsp = service.locate(create_sale_rsp['body'])
        print('locate_rsp', locate_rsp)

        soft_id = [soft['id'] for soft in module_service.find_soft()['body'] if soft['cd'] == BBP_SOFT_CODE][0]

        modules = service.find_all(create_sale_id, soft_id)['body']

        print('modules', modules)

        rsp = service.save_module(create_sale_id, soft_id, Modules)
        print("save module rsp", rsp)

        sale_id = [sale['key'] for sale in service.sales() if sale['text'] == BALANCE_SOFT_NAME][0]
        print('sale_id = ' + str(sale_id))

        service = TenantConfigService(client)
        rsp = service.create_tenant(tenant_code, '对账管理', sale_id)
        print(rsp)


def add_module_to_tenant():
    client = system_client()

    service = TenantConfigService(client)
    rsp = service.load_apps()

    bsoft_bbp = [item for item in rsp['body'] if item['cd'] == 'bsoft-bbp'][0]

    bsoft_bbp_id = bsoft_bbp['id']

    print('bsoft_bbp_id:' + bsoft_bbp_id)

    rsp = service.load_module_tree(Default_tenant_id, bsoft_bbp_id)

    print(rsp['body'])

    rsp = service.save_tenant_module(Default_tenant_id, bsoft_bbp_id, rsp['body'])

    print(rsp)


def setup_soft_and_module():
    client = tenant_client()
    module_service = ModuleService(client)

    b, balance_soft_id = module_service.exist_soft(BALANCE_SOFT_CODE)

    if balance_soft_id is None:
        soft = module_service.save_soft(BALANCE_SOFT_CODE, BALANCE_SOFT_NAME)
        balance_soft_id = soft['body']['id']
        print('create balance soft:', balance_soft_id)
    else:
        print('find balance soft:', balance_soft_id)

    balance_soft_info = module_service.get_module_category_by_soft(balance_soft_id)['items']
    print(balance_soft_info)
    b, ca_id = module_service.exist_module_category_with_soft(balance_soft_id, 'fuca-balance-result')
    if ca_id is None:
        module_ca = module_service.save_module_category('fuca-balance-result', '对账结果', balance_soft_id)['body']
        print('new module_ca:', module_ca)
        ca_id = module_ca['id']
    print('ca_id:', ca_id)

    b, module_id = module_service.exist_module_with_ca_id('fu-balance-result-daily', ca_id)
    if module_id is None:
        module_category = module_service.get_module_category(ca_id)['body']
        print('module_category:', module_category)
        module = module_service.save_module(module_category, 'fu-balance-result-daily', '日对账结果')['body']
        print('module:', module)
        module_id = module['id']

    print('module_id:', module_id)
    module_prop = module_service.exist_module_prop('url', module_id)
    if module_prop is None:
        module_service.save_module_prop(module_id, 'url', 'cn.com.bsoft.balance.portal.page.DailyBalanceRecord')





if __name__ == '__main__':
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    create_tenant()
    # add_module_to_tenant()
    #setup_soft_and_module()
    # client = SsdevClient(Default_bbp_url, Default_bbp_url)
    #
    # tenant_id = Default_tenant_id
    # username = Default_username
    # password = Default_password
    #
    # rsp = client.my_roles(tenant_id, username, password)
    # my_roles = rsp['body']
    #
    # token = client.fetch_token(tenant_id, username, my_roles[0])
    # main(client)
